<template>
	<div ref="viewerRef"></div>
</template>

<script setup>
import { Viewer, utils } from '@photo-sphere-viewer/core';
import { MarkersPlugin } from '@photo-sphere-viewer/markers-plugin';
import { GalleryPlugin } from '@photo-sphere-viewer/gallery-plugin';
import { AutorotatePlugin } from '@photo-sphere-viewer/autorotate-plugin';
import { EquirectangularTilesAdapter } from '@photo-sphere-viewer/equirectangular-tiles-adapter';
import { VisibleRangePlugin } from '@photo-sphere-viewer/visible-range-plugin';
import '@photo-sphere-viewer/core/index.css';
import '@photo-sphere-viewer/markers-plugin/index.css';
import '@photo-sphere-viewer/gallery-plugin/index.css';
import { getUuid } from '../../utils/base';
import { ref, onMounted, reactive, toRefs, defineEmits, defineExpose, computed, h } from 'vue';
import { useRoute } from 'vue-router';
import { getCzDzbData, listQjPoi, getQjPoi } from './service';
const route = useRoute();
const baseUrl = 'https://photo-sphere-viewer-data.netlify.app/assets/';
const viewerRef = ref(null);
//全景图viewer

let viewer = null;
//全景图视角配置
let animatedValues = {
	pitch: { start: Math.PI, end: 0 },
	yaw: { start: -Math.PI, end: 0 },
	zoom: { start: 0, end: 10 },
	fisheye: { start: 2, end: 0 }
};
//全景图像上添加标记(markers)或热点(hotspots)插件
let markersPlugin = null;
//自动旋转功能插件
let autorotatePlugin = null;
//创建全景图像的画廊插件
let galleryPlugin = null;
let equirectangular = null;
//限制显示范围插件
let visibleRangePlugins = null;
defineExpose({ updateIndex, handelChangeViewer, galleryHide, galleryShow, initBigPhotos });
const emit = defineEmits(['selectMarker', 'changetooOften']);
const info = reactive({
	currIndex: 0,
	panoramaUrl: null,
	markerList: [],
	picsList: [],
	galleryList: [],
	poiObj: {}
});

let { currIndex, panoramaUrl, markerList, picsList, poiObj, galleryList } = toRefs(info);
let prefixUrl = computed(() => {
	return panoramaUrl.value.substring(0, panoramaUrl.value.lastIndexOf('.'));
});
onMounted(async () => {
	initViewer();
	await initBigPhotos();
	handleSelectMarker();
});
/**
 * @description: 全景图的基础配置
 * @param {*} params
 * @return {*}
 */
function initViewer() {
	viewer = new Viewer({
		container: viewerRef.value,
		caption: '党建全景图',
		loadingImg: baseUrl + 'loader.gif',
		mousewheelCtrlKey: false, // 是否需要使用ctrl键缩放全景
		// defaultPitch: animatedValues.pitch.start, //默认垂直视角（俯仰角）
		// defaultYaw: animatedValues.yaw.start, //默认水平视角（偏航角）
		//fisheye: animatedValues.fisheye.start, //实现鱼眼效果
		//fisheye: true,
		navbar: false,
		//defaultZoomLvl: 50,
		adapter: EquirectangularTilesAdapter,
		plugins: [
			[
				GalleryPlugin,
				{
					visibleOnLoad: true,
					// hideOnClick: false,
					thumbnailSize: {
						width: 80,
						height: 80
					}
				}
			],
			[
				AutorotatePlugin,
				{
					autostartDelay: 3000,
					autorotatePitch: '-20deg',
					autostartOnIdle: true,
					autorotateSpeed: '1rpm'
				}
			],
			[
				MarkersPlugin,
				{
					markers: []
				}
			],
			[
				VisibleRangePlugin,
				{
					//horizontalRange: [-Math.PI / 2, Math.PI / 2],
					verticalRange: [-Math.PI / 2, Math.PI / 10]
				}
			]
		]
	});
	//获取已经添加到查看器实例中的插件
	markersPlugin = viewer.getPlugin(MarkersPlugin);
	autorotatePlugin = viewer.getPlugin(AutorotatePlugin);
	equirectangular = new EquirectangularTilesAdapter(viewer);

	galleryPlugin = viewer.getPlugin(GalleryPlugin);
	visibleRangePlugins = viewer.getPlugin(VisibleRangePlugin);
	//全景图像查看器准备好并可用时触发回调函数
	viewer.addEventListener('ready', handleViewerReady, {
		once: true
	});
}
async function handleViewerReady() {
	//enteraAimation();
	// setTimeout(() => {
	// 	intro(animatedValues.pitch.end, animatedValues.pitch.end);
	// }, 5000);
	// await initMarkerList();
	// if (markerList.value.length > 1) {
	// 	//autorotatePlugin.setKeypoints(markerList.value);
	// }
}
/**
 * @description: 切换场景图
 * @param {*} mold
 * @param {*} index
 * @return {*}
 */
function updateIndex(mold, index) {
	switch (mold) {
		//普通大全景图
		case 'type':
			getQjPoi(index).then(({ data }) => {
				picsList.value = JSON.parse(data.qjturls);
				poiObj.value = JSON.parse(data.obj);
				initGalleryInit(picsList.value);
				setTimeout(() => {
					currIndex.value = 0;
					handelChangeViewer('mark', poiObj.value[`poi0`], 0);
					handleGalleryChange();
					emit('playMp3');
				});
			});
			break;
		//小全景图跳转
		case 'skip':
			currIndex.value = index;
			handelChangeViewer('mark', poiObj.value[`poi${index}`], index);
			break;
		default:
			break;
	}
}

/**
 * @description: 点击marker事件
 * @param {*} type
 * @param {*} pois
 * @param {*} currIndex
 * @return {*}
 */
function handelChangeViewer(type, pois, currIndex) {
	emit('changetooOften', true); //处理频繁切换问题
	if (viewer) {
		clearMarker();
		if (type == 'gallery') {
			//点击图库切换
			setDefaultOptions();
			initPoi(pois);
			galleryShow();
			handelGalleryActive();
			markersPlugin.showAllTooltips();
			emit('changetooOften', false);
			visibleRangePlugins.setVerticalRange([-Math.PI / 4, Math.PI / 2]);
			autorotatePlugin.config.autorotatePitch = 0;
		} else {
			//标记几自定义切换场景
			if (panoramaUrl.value) {
				let panoramaUrls = {
					width: 2000,
					cols: 32,
					rows: 16,
					baseUrl: picsList.value[currIndex],
					tileUrl: (col, row) => {
						return `${picsList.value[currIndex].substring(
							0,
							picsList.value[currIndex].lastIndexOf('.')
						)}_${row}_${col}.jpg`;
					}
				};
				visibleRangePlugins.setVerticalRange([-Math.PI / 4, Math.PI / 2]);
				autorotatePlugin.config.autorotatePitch = 0;
				viewer.setPanorama(panoramaUrls).then(res => {
					initPoi(pois);
					galleryShow();
					handelGalleryActive();
				});
			} else {
				emit('changetooOften', false);
			}
		}
	}
}

/**
 * @description: 清除所有标记
 * @return {*}
 */
function clearMarker() {
	markersPlugin.clearMarkers();
}

/**
 * @description: 恢复默认视角
 * @return {*}
 */
function setDefaultOptions() {
	viewer.rotate({ yaw: 0, pitch: 0 });
}
/**
 * @description: 全景图视图初始化
 * @return {*}
 */

/**
 * @description: 初始化动画
 * @return {*}
 */
function enteraAimation() {
	new utils.Animation({
		properties: animatedValues,
		duration: 2500,
		easing: 'inOutQuad',
		onTick: properties => {
			viewer.setOption('fisheye', properties.fisheye);
			viewer.rotate({ yaw: properties.yaw, pitch: properties.pitch });
			viewer.zoom(properties.zoom);
		}
	}).then(() => {
		//if (props.hasGallery) {
		//在某个时刻更新画廊中的全景图像项
		// galleryPlugin.setItems();
		//设置标签//设置图库
		//}
	});
}
/**
 * @description:展示所有标记信息
 * @return {*}
 */
function showInitMarker() {
	//用于显示所有已添加标记的工具提示
	markersPlugin.showAllTooltips();
}

/**
 * @description: 选择标记事件
 * @return {*}
 */
function handleSelectMarker() {
	markersPlugin.addEventListener('select-marker', ({ marker }) => {
		emit('selectMarker', marker);
	});
}

//gallery图库列表切换
function galleryShow() {
	galleryPlugin.show();
}
function galleryHide() {
	galleryPlugin.hide();
}
function galleryToggle() {
	galleryPlugin.toggle();
}
/**
 * @description: 底部导航切换事件
 * @return {*}
 */
function handleGalleryChange() {
	let _sindex = '';
	document.addEventListener('click', function (e) {
		let element = document.elementFromPoint(e.clientX, e.clientY);
		let flag = false;
		if (element && element.dataset && element.dataset.psvGalleryItem) {
			const id = element.dataset.psvGalleryItem;
			_sindex = galleryList.value.findIndex(data => {
				return data.id == id;
			});
			flag = true;
		} else {
			if (element && element.className == 'psv-gallery-item-thumb') {
				const eleId = element.parentElement.parentElement.dataset.psvGalleryItem;
				_sindex = galleryList.value.findIndex(data => {
					return data.id == eleId;
				});
				flag = true;
			}
		}

		if (flag) {
			currIndex.value = _sindex;
			handelChangeViewer('gallery', poiObj.value[`poi${_sindex}`], _sindex);
		} else {
			/*  console.log(" _sindex不存在"); */
		}
	});
}

/**
 * @description: 底部导航选中事件
 * @return {*}
 */
function handelGalleryActive() {
	const galleryBox = document.getElementsByClassName('psv-gallery-container')[0];
	if (currIndex.value !== '' && document.getElementsByClassName('psv-gallery-item')[currIndex.value]) {
		const galleryItemEle =
			document.getElementsByClassName('psv-gallery-item')[currIndex.value] ||
			document.getElementsByClassName('psv-gallery-item');
		galleryBox.childNodes.forEach(item => {
			item.className = 'psv-gallery-item';
		});
		galleryItemEle.classList.add('psv-gallery-item--active');
	}
}
function intro(pitch, yaw) {
	new utils.Animation({
		properties: {
			...animatedValues,
			pitch: { start: animatedValues.pitch.start, end: pitch },
			yaw: { start: animatedValues.yaw.start, end: yaw }
		},
		duration: 2500,
		easing: 'inOutQuad',
		onTick: properties => {
			viewer.setOptions({
				fisheye: properties.fisheye,
				maxFov: properties.maxFov
			});
			viewer.rotate({ yaw: properties.yaw, pitch: properties.pitch });
			viewer.zoom(properties.zoom);
		}
	}).then(() => {
		viewer.setOptions({
			mousemove: true,
			mousewheel: true
		});
	});
}
/**
 * @description:初始化大全景图
 * @return {*}
 */
async function initBigPhotos() {
	return new Promise((resolve, reject) => {
		getCzDzbData({ id: route.query.id }).then(res => {
			panoramaUrl.value = res.qjturl;
			let panoramaUrls = {
				width: 2000,
				cols: 32,
				rows: 16,
				baseUrl: panoramaUrl.value,
				tileUrl: (col, row) => {
					return `${prefixUrl.value}_${row}_${col}.jpg`;
				}
			};
			visibleRangePlugins.setVerticalRange([-Math.PI / 2, Math.PI / 10]);
			viewer.setPanorama(panoramaUrls).then(async res => {
				await initMarkerList();
				if (markerList.value.length > 1) {
					autorotatePlugin.setKeypoints(markerList.value);
				}
				galleryList.value = [];
				resolve();
			});
		});
	});
}
/**
 * @description: 初始化全景点位
 * @return {*}
 */
async function initMarkerList() {
	return new Promise((resolve, reject) => {
		listQjPoi({
			pageNum: 1,
			pageSize: 10,
			cunzhenId: route.query.id
		}).then(res => {
			initMarkers(res.rows);
			resolve();
		});
	});
}
/**
 * @description: 初始化底部导航信息
 * @param {*} list
 * @return {*}
 */
function initGalleryInit(list) {
	list &&
		list.forEach((item, index) => {
			let panoramaUrls = {
				width: 20000,
				cols: 32,
				rows: 16,
				baseUrl: item,
				tileUrl: (col, row) => {
					return `${item.substring(0, item.lastIndexOf('.'))}_${row}_${col}.jpg`;
				}
			};
			let urlHeard = item.substring(0, item.lastIndexOf('/') + 1);
			let urlName = 'SLT_' + item.substring(item.lastIndexOf('/') + 1);
			let gallery = {
				id: 'gallery' + index,
				panorama: panoramaUrls,
				thumbnail: urlHeard + urlName,
				options: {
					caption: 'Parc national du Mercantour <b>&copy; Damien Sorel</b>'
				}
			};
			galleryList.value.push(gallery);
		});
	galleryPlugin.setItems(galleryList.value);
}

/**
 * @description: 点位数据初始化
 * @return {*}
 */
function initMarkers(values) {
	values &&
		values.forEach(item => {
			let { x, y } = JSON.parse(item.location);
			let marker = {
				id: getUuid(),
				position: {
					yaw: x,
					pitch: y
				},
				image: item.picType,
				size: {
					width: 40,
					height: 40
				},
				anchor: 'bottom center',
				tooltip: {
					content: item.name,
					className: 'bigTooltip',
					position: 'bottom',
					trigger: 'click'
				},
				content: item.content,
				type: item.type,
				pics: item.pics,
				poiId: item.id
			};
			markersPlugin.addMarker(marker);
			markerList.value.push(marker);
		});
	showInitMarker();
}
/**
 * @description: 初始化poi点位信息
 * @param {*} values
 * @return {*}
 */
function initPoi(values) {
	values &&
		values.forEach(item => {
			let marker = {
				id: getUuid(),
				position: {
					yaw: item.yaw,
					pitch: item.pitch
				},
				image: item.selectedIdx,
				size: {
					width: 40,
					height: 40
				},
				anchor: 'bottom center',
				tooltip: {
					content: item.content,
					className: 'bigTooltip',
					position: 'bottom',
					trigger: 'click'
				},
				content: item?.briefMsg,
				skip: item?.skip,
				skipIndex: item?.skipIndex,
				pics: item?.briefPic
			};
			markersPlugin.addMarker(marker);
			markerList.value.push(marker);
		});
	showInitMarker();
}
</script>

<style lang="scss">
.psv-gallery {
	background: none;
	border: none;
	z-index: 88;
	pointer-events: none;
}

.psv-gallery-container {
	justify-content: center;
}

.psv-gallery.psv-gallery--open {
	transform: translateY(-20px) !important;
}

.psv-gallery-item {
	pointer-events: auto;
}

.psv-gallery-item::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	box-sizing: border-box;
	border: 3px solid white;
	z-index: 3;
}

.psv-gallery-item--active::after {
	/*  rgb(246, 166, 0) */
	border-color: rgb(246, 166, 0);
}

.psv-gallery-item-title {
	bottom: 0;
	top: auto;
	font-size: 12px;
}

.psv-gallery-item:hover .psv-gallery-item-title {
	height: 2.2em;
}

.psv-panel {
}
</style>
